package com.kxf.androidtestdemo.view;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;

import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.kxf.androidtestdemo.R;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LogTxtView extends ScrollView {
    private View viewRoot;
    private TextView tv;
    private StringBuilder sb = new StringBuilder();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");

    public LogTxtView(Context context) {
        super(context);
        init(context, null);
    }

    public LogTxtView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public LogTxtView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public LogTxtView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
        viewRoot = inflater.inflate(R.layout.layout_log_view, this);
        tv = viewRoot.findViewById(R.id.tv);
    }

    public void showTxt(String txt){
        post(new Runnable() {
            @Override
            public void run() {
                sb.append(sdf.format(new Date()) + "==>>" + txt + "\n" + "\n");
                tv.setText(sb.toString());
            }
        });
    }

    public void clearTxt(){
        post(new Runnable() {
            @Override
            public void run() {
                sb = new StringBuilder();
                tv.setText(sb.toString());
            }
        });
    }
}
